<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :exclude-values="['userCName', 'roleCName', 'endTime']"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
      @reset="resetFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="roleCName" label="角色">
          <FIAutoInput
            v-model="state.query.roleCName"
            :options="postList"
            value-key="roleCName"
            :display-key="['roleEName', 'roleCName']"
            @select="selectClick($event)"
            @change="changeEvent($event)"
          >
            <template #default="{ item }">
              <div>{{ item.roleCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="startTime" label="发起时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="date"
            placeholder="发起时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="date"
            placeholder="发起时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processName" label="流程名称">
          <ProcessName v-model="state.query.processDefKey"></ProcessName>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="completerId" label="处理人">
          <FIAutoSelect
            v-model="state.query.completerId"
            :props="{ value: 'loginName', label: 'userName' }"
            :display-key="['loginName', 'userName']"
            api-url="/rm2/userMaint/query"
            searchParam="userAName"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="instStatus" label="流程状态">
          <FISelect v-model="state.query.instStatus" valueCustom="value" :options="processStatus" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="查询结果"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="processDefName"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
    <FIModel v-model="detailShow" title="查询结果明细" @close="detailShow = false">
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="detailList"
        primaryKey="processDefKey"
        :showSaveModel="false"
        :rowNo="true"
        v-model:columns="columns1"
        :insertable="false"
        :isLoading="isTableLoading2"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig2"
        :settingConfig="settingConfig"
        @size-change="handleSizeChange2"
        @current-page-change="handleCurrentChange2"
      >
      </FITable>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <FIButton @click="detailShow = false">关闭</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import ProcessName from '../../components/ProcessName.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryVote,
  apiQueryProcessesDef,
  apiQueryUser,
  apiQueryRoles,
  apiQueryAllBpmCatogary,
  apiPersDownload,
  apiBranDownload,
  apiQueryProcessPer,
  apiQueryDetail,
} from '@/api/modules/EW.js'
const route = useRoute()
const loadMoreEnd = ref(false)
const processPage = ref(1)
const searchWrapperSpan = 8
const processArr = ref([])
const isTableLoading = ref(false)
const isTableLoading2 = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const userList = ref([])
const postList = ref([])
const detailShow = ref(false)
const detailList = ref([])
// completerFullname1 处理人
// processDefName1 流程定义名称
// startTime 发起开始时间
// endTime 发起结束时间
// instStatus 流程状态
// processDefKey 流程定义编码
// taskName 节点名称
// taskStatus 任务状态
const completerFullname = ref('')
const processDefKey = ref('')
const processDefName = ref('')
const taskName = ref('')
const taskStatus = ref('')
const instStatus = ref('')
const startTime = ref('')
const endTime = ref('')
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const state = reactive({
  query: {
    roleCName: '',
    roleEname: '',
    startTime: '',
    completerId: '',
    processDefKey: '',
    endTime: '',
    instStatus: '',
    current: 1,
    size: 10,
    userCName: '',
    
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const pageConfig2: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const processStatus = [
  {
    value: 'active',
    label: '正运行',
  },
  {
    value: 'suspend',
    label: '挂起',
  },
  {
    value: 'finish',
    label: '结束',
  },
  {
    value: 'manual-finish',
    label: '终止',
  },
]
const columns1: Column[] = reactive([
  {
    label: '发起部门',
    prop: 'deptName',
    align: 'center',
    editType: 'input',
  },
  {
    label: '流程名称',
    prop: 'processDefName',
    align: 'center',
    editType: 'input',
  },
  {
    label: '流程实例',
    prop: 'sequenceId',
    align: 'center',
    editType: 'input',
  },
  {
    label: '节点名称',
    prop: 'taskName',
    align: 'center',
    editType: 'input',
  },
  {
    label: '任务到达时间',
    prop: 'startTime',
    align: 'center',
    editType: 'time-picker',
  },
  {
    label: '任务完成时间',
    prop: 'endTime',
    align: 'center',
    editType: 'time-picker',
  },
  {
    label: '任务耗时',
    prop: 'maxTime',
    align: 'center',
    editType: 'input',
  },
])
const columns: Column[] = reactive([
  {
    label: '处理人',
    prop: 'completerFullname',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '流程名称',
    prop: 'processDefName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '节点名称',
    prop: 'taskName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '任务数量',
    prop: 'taskCount',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '任务状态',
    prop: 'taskStatus',
    align: 'center',
    editType: 'select',
    editConfig: {
      options: [
        {
          value: 'completed',
          label: '完成',
        },
        {
          value: 'open',
          label: '正运行',
        },
        {
          value: 'suspend',
          label: '暂停',
        },
        {
          value: 'closed',
          label: '终止',
        },
      ],
    },
  },
  {
    label: '全流程平均时效（单位：小时）',
    prop: 'maxTime',
    sortable:true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'detail', type: 'top' }],
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleSizeChange2 = (e) => {
  pageConfig2.pageSize = e
  pageConfig2.currentPage = 1
  getDetailFn()
}
const changeEvent = (e) => {
  if (!e) {
    // if (type == 'fq_dept') state.query.startDeptId = ''
  }
}
const selectClick = (data) => {
  state.query.roleEname = data.roleEName
}
const resetFn = () => {
  state.query.roleCName = ''
  state.query.userCName = ''
  // state.query.categoryName = ''
  // state.query.productName = ''
}
//导出
const exportClick = () => {
  apiPersDownload(state.query)
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  console.log(rowData, 'rowData')
  completerFullname.value = rowData.completerFullname
  // processDefKey.value = rowData.processDefKey
  taskName.value = rowData.taskName
  taskStatus.value = rowData.taskStatus
  // instStatus.value = rowData.instStatus
  detailShow.value = true
  processDefName.value = rowData.processDefName
  // startTime.value = rowData.startTime
  // endTime.value = rowData.endTime
  getDetailFn()
}
const getDetailFn = () => {
  let par = {
    processDefKey: state.query.processDefKey,
    taskName: taskName.value,
    taskStatus: taskStatus.value,
    instStatus: state.query.instStatus,
    processDefName1: processDefName.value,
    completerFullname1: completerFullname.value,
    startTime: state.query.startTime,
    endTime: state.query.endTime,
    current: pageConfig2.currentPage,
    size: pageConfig2.pageSize || 10,
  }
  isTableLoading2.value = true
  apiQueryDetail(par)
    .then((res) => {
      isTableLoading2.value = false
      if (res.data.success) {
        detailList.value = res.data.data.result
        pageConfig2.pageSize = Number(res.data.data.size)
        pageConfig2.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading2.value = false
    })
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const handleCurrentChange2 = (e) => {
  pageConfig2.currentPage = e
  getDetailFn()
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiQueryProcessPer(state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const getBJlist = () => {
  apiQueryVote({ vote: '' })
    .then((res) => {
      if (res.data.success) {
        // saveSuccessful.value = true
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {})
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  let par = {
    current: 1,
    size: 999,
  }
  apiQueryRoles(par)
    .then((res) => {
      if (res.data.success) {
        postList.value = res.data.data
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const processloadMore = () => {
  if (loadMoreEnd.value && processPage.value > 1) return
  processPage.value++
  getQueryAll()
}
const getQueryAll = () => {
  let par = {
    current: processPage.value,
    size: 10,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      if (res.data.success) {
        processArr.value = processArr.value.concat(res.data.data.result)
        if (processPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  getBJlist() //获取表决数据
  getQueryAll() //查询流程名称
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()//初始化不掉数据
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
